import Vue from "vue";
import VueRouter from "vue-router";

import Layout from '@/layout'
import Login from '@/views/login'
import NotFind from '@/views/error/404'
import Forbidden from '@/views/error/403'

Vue.use(VueRouter);

// 解决在当前路由的时候点击当前路由

//获取原型对象上的push函数
const originalPush = VueRouter.prototype.push;
//修改原型对象中的push方法
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
};

export const constantRoutes = [
    {
        path: "/login",
        name: "login",
        component: Login,
        meta: {
            requiresAuth: false
        }
    }
];

/**
 * 根据权限判断页面
 *
 * 例如: admin ---> 所有页面
 *
 */
// 默认动态路由
export const defaultDynamicRoutes = [
    {
        path: "/",
        name: "Layout",
        component: Layout,
        redirect: "home",
        meta: {
            requiresAuth: true,
            name: "首页"
        },
        children: []
    },
    {
        path: "/forbidden",
        name: "Forbidden",
        component: Forbidden
    },
    {
        path: "*",
        name: "NotFind",
        component: NotFind
    }
];

const createRouter = () => new VueRouter({
    mode: 'history', // require service support
    base: process.env.BASE_URL,
    routes: constantRoutes
});

const router = createRouter();

/**
 * 重置路由  重置当前动态路由 由于页面不刷新 defaultDynamicRoutes 为增加后的状态
 */
export function resetRouter() {
    const newRouter = createRouter();
    defaultDynamicRoutes[0].children = [];
    router.matcher = newRouter.matcher // reset router
}

export default router;
